<template>
  <div>
    <!-- 登录页面：已完成 -->
    <!-- 导航栏部分 -->
    <div class="nav">
      <router-link class="left" to="/">
        <img src="./imgs/left(white).svg" height="20px" width="20px" />
      </router-link>
      <div class="center">登录</div>
      <div class="right" @click="onClickRight">{{ msg }}</div>
    </div>

    <!-- 背景图 -->
    <div class="pic1 pwdPic" v-show="showPic">
      <p>夏日粥铺</p>
    </div>
    <div class="pic2 pwdPic" v-show="!showPic">
      <p>夏日粥铺</p>
    </div>

    <!-- 登录框 -->
    <!-- 密码登录 -->
    <div class="login" v-if="code">
      <div class="phone">
        <div class="left-text">手机号</div>
        <input
          type="text"
          placeholder="请输入您的手机号"
          value="phone"
          v-model="phone"
        />
      </div>
      <div class="pwd">
        <div class="left-text">密&nbsp;&nbsp;&nbsp;码</div>
        <input
          type="text"
          placeholder="请输入密码"
          value="upwd"
          v-model="upwd"
          ref='inputPwd'
          @focus="showPic = false"
          @blur="showPic = true"
          v-show="showPwd"
        />
        <input
          type="password"
          placeholder="请输入密码"
          value="upwd"
          v-model="upwd"
          ref='inputPwd'
          @focus="showPic = false"
          @blur="showPic = true"
          v-show="!showPwd"
        />
        <span class="switch" @click="showPwd = !showPwd">
          <img src="./imgs/show.svg" v-show="showPwd">
          <img src="./imgs/hidden.svg" v-show="!showPwd">
        </span>
      </div>
    </div>

    <!-- 短信验证码登录 -->
    <div class="login" v-else>
      <div class="phone">
        <div class="left-text">手机号</div>
        <input 
        type="text" 
        placeholder="请输入您的手机号"
        value="phone"
        v-model="phone" />
      </div>
      <div class="pwd">
        <div class="left-text">短信验证码</div>
        <input type="password" placeholder="请输入验证码" />
        <button 
        :class="{right_phone:rightPhone}" 
        :disabled='!rightPhone'
        @click="getCode"
        >
        {{computeTime?`已发送(${computeTime}s)`:'发送验证码'}}
        </button>
      </div>
    </div>

    <!-- 登录按钮部分 -->
    <button class="btn" @click="checkForm">登录</button>
    <div class="bottom">
      <img src="./imgs/login1.png" height="50px" />
      <router-link to="/register">还不是会员？赶紧注册一个吧~</router-link>
    </div>
  </div>
</template>

<script>
// 引入头部子组件（带插槽）
import HeaderTop from "../../components/HeaderTop/HeaderTop";
import { setInterval, clearInterval } from "timers";

export default {
  name: "Login",
  components: { HeaderTop },
  data() {
    return {
      code: true,
      msg: "短信验证码登录",
      phone: "",
      upwd: "",
      computeTime: 0, //发送验证码倒计时
      showPic: true, //密码框获得焦点时，背景图的变化
      showPwd: false
    };
  },
  computed: {
    rightPhone() {
      return /^1[3-9]\d{9}$/.test(this.phone);
    }
  },
  methods: {
    onClickRight() {
      if (this.code) {
        this.code = false;
        this.msg = "密码登录";
      } else {
        this.code = true;
        this.msg = "短信验证码登录";
      }
    },
    // 验证手机号是否正确
    checkPhone() {
      let reg = /^1[3-9]\d{9}$/;
      if (reg.test(this.phone)) {
        return true;
      } else {
        this.$toast({
          message: "手机号格式不正确！",
          position: "center",
          duration: 3000
        });
        return false;
      }
    },
    // 验证密码格式
    checkUpwd() {
      let reg = /^\w{6,20}$/;
      if (reg.test(this.upwd)) {
        return true;
      } else {
        this.$toast({
          message: "密码格式不正确！",
          position: "center",
          duration: 3000
        });
        return false;
      }
    },
    // 获取验证码
    getCode() {
      //启动倒计时
      if (!this.computeTime) {
        //当 computeTime 为0时，说明此时还没开始计时
        this.computeTime = 60;
        const countDown = setInterval(() => {
          this.computeTime--;
          if (this.computeTime === 0) {
            clearInterval(countDown);
          }
        }, 1000);
      }
    },
    // 点击提交按钮后，发送 axios 请求
    checkForm() {
      if (this.checkPhone() && this.checkUpwd()) {
        // alert("发送axios请求");
        this.axios
          .post("/api/user/tologin", `phone=${this.phone}&userPwd=${this.upwd}`)
          .then(result => {
            // console.log(result);
            var res = result.data;
            if (res.code == 402) {
              this.$toast({
                message: `${res.message}`,
                position: "center",
                duration: 3000
              });
            } else if (res.code == 200) {
              this.$toast({
                message: `登录成功！`,
                position: "center",
                duration: 3000
              });
              // 登录成功后，执行 mutations 更新 vuex 中的 用户状态信息
              // console.log(res.data.userId);
              this.$store.commit("setIsLogin", res.data.userId);
              // 同时将登录状态也存储一份在 sessionStorage 中
              sessionStorage.setItem("isLogin", "true");
              sessionStorage.setItem("userId", res.data.userId);

              sessionStorage.setItem("addressTitle", "暂时无法获取定位");
              sessionStorage.setItem("addressDetail", "暂无对应地址");
              // console.log(this.$store.state.isLogin, this.$store.state.userId);
              this.$router.push("/");
            }
          });
      }
    }
  }
};
</script>

<style lang='scss' scoped>
/* 导航栏部分 */
.nav {
  height: 40px;
  background-color: #26a2fe;
  color: white;
  line-height: 40px;
}

.nav > .center {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
}

.nav > .left {
  width: 30px;
  margin: 0 10px;
  background: url(/imgs/left.png) no-repeat;
  /* background-color: black; */
}

.nav > .right {
  position: absolute;
  font-size: 12px;
  right: 8px;
}

.pwdPic {
  width: 100%;
  height: 90px;
  p {
    text-align: center;
    line-height: 70px;
    font-size: 20px;
    font-weight: 700;
    color: #48cfe5;
  }
}
.pic1 {
  background: url(./imgs/b1.png);
  background-size: 100% 100%;
}
.pic2 {
  background: url(./imgs/b2.png);
  background-size: 100% 100%;
}

/* 登录框部分 */
.login {
  position: relative;
  /* background-color: pink; */
  height: 100px;
  width: 100%;
  margin-top: 10px;
}
.phone,
.pwd {
  width: 100%;
  position: absolute;
  padding-left: 10px;
  height: 35px;
  border-bottom: 1px solid #edeff2;
}
.left-text {
  position: absolute;
  text-align: center;
  line-height: 30px;
}
/* 给所有的输入框和按钮设置公共样式 */
input {
  position: absolute;
  left: 100px;
  border: none;
  height: 30px;
}
::-webkit-input-placeholder {
  color: #cbc9d5;
}
button {
  border: none;
}
.pwd {
  top: 55px;
  .right_phone {
    color: black;
  }
  .switch {
    float: right;
    margin-right: 15px;
    img {
      height: 30px;
    }
  }
}
.pwd > input {
  width: 120px;
}
/* 发送验证码按钮 */
.pwd > button {
  float: right;
  padding: 0 15px;
  font-size: 14px;
  margin: 3.5px 8px;
  background-color: #fff;
  border-left: 1px solid #cbc9d5;
  color: #cbc9d5;
}
/* 登录按钮 */
.btn {
  width: 95%;
  background-color: #26a2fe;
  margin: 8px;
  color: white;
  border-radius: 5px;
}
/* 底部注册提示 */
.bottom {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  text-align: center;
}
.bottom > a {
  text-decoration: none;
  font-size: 16px;
  color: #f44336;
}
</style>
